'use strict';

const db = uniCloud.database();
const dbcmd = db.command;
const wmzAlipaySdk = uniCloud.importObject('wmz-alipay-sdk')
exports.main = async (event, context) => {
	let response = {
		code: 0
	};
	const ip = context.CLIENTIP;
	await doOrderSync(ip);
	//返回数据给客户端
	return response;
};

const doOrderSync = async (ip) => {
	let orderRes = await db.collection('wmzmall-order')
		.where({
			self_pick:true,
			order_pay_way: "支付宝支付",
			order_sync: dbcmd.neq('FINISHED').and(dbcmd.neq('CREATE_ERROR')).and(dbcmd.neq(
				'IN_DELIVERY_ERROR')).and(dbcmd.neq('FINISHED_ERROR')),
			state: dbcmd.eq("待发货").or(dbcmd.eq("待收货")).or(dbcmd.eq("待评价")).or(dbcmd.eq("已完成"))
		})
		.limit(1000)
		.orderBy('create_time','desc')
		.get();
	orderRes = orderRes.data
	uniCloud.logger.info("查询返佣数据"+orderRes.length+"条")
	console.log(orderRes)
	let business_info = {
		isv_id: '2088331963340633',
		come_again: ''
	}
	let biz_content = {}
	let ext_info = []
	let syncData
	let orderSync
	let order
	let orderDetailRes
	let orderSyncRes
	let merchant_order_status
	let bsync
	for (var i in orderRes) {
		bsync = false
		order = orderRes[i]
		biz_content = {
			out_biz_no: order._id,
			buyer_id: order.order_member_openid,
			order_type: "SERVICE_ORDER",
			order_create_time: await formatdate(order.order_pay_time),
			order_modified_time: await formatdate(order.order_pay_time),
			"shop_info": {
				"merchant_shop_id": order.alipay_shop_id
			}
			// trade_no: outTradeNo,
			// trade_type: "TRADE", 
		}
		let merchant_biz_type
		if(order.self_pick){
			merchant_biz_type='KX_SELF_PICK'
			if (order.state === '待发货') {
				if (!order.order_sync) {
					merchant_order_status = 'TO_PICK_UP'
					biz_content.ticket_info={
						resv_type:'INSTANT'
					}
					bsync = true
				}
			}else if (order.state === '已完成'||order.state ==='待评价') {
				if (order.order_sync === 'TO_PICK_UP') {
					merchant_order_status = 'FINISHED'
					biz_content.ticket_info={
						resv_type:'INSTANT'
					}
					bsync = true
				}
			}
			
		}else{
			merchant_biz_type='KX_SHOPPING'
			if (order.state === '待发货') {
				if (!order.order_sync) {
					merchant_order_status = 'CREATE'
					bsync = true
				}
			} else if (order.state === '待收货') {
				if (!order.order_sync) {
					merchant_order_status = 'CREATE'
					bsync = true
				} else if (order.order_sync === 'CREATE') {
					merchant_order_status = 'IN_DELIVERY'
					biz_content.order_modified_time = await formatdate(order.order_expire_time)
					business_info.courier_number = order.order_express_no
					let logistics_code = ""
					if (order.order_express === "顺丰速运") {
						logistics_code = "SF"
					}
					biz_content.logistics_info_list = {
						logistics_code: logistics_code,
						tracking_no: order.order_express_no
					}
					bsync = true
				}
			} else if (order.state === '已完成'||order.state ==='待评价') {
				if (!order.order_sync) {
					merchant_order_status = 'CREATE'
					bsync = true
				} else if (order.order_sync === 'CREATE') {
					merchant_order_status = 'IN_DELIVERY'
					biz_content.order_modified_time = await formatdate(order.order_expire_time)
					business_info.courier_number = order.order_express_no
					let logistics_code = ""
					if (order.order_express === "顺丰速运") {
						logistics_code = "SF"
					}
					biz_content.logistics_info_list = {
						logistics_code: logistics_code,
						tracking_no: order.order_express_no
					}
					bsync = true
				} else if (order.order_sync === 'IN_DELIVERY') {
					merchant_order_status = 'FINISHED'
					biz_content.order_modified_time = await formatdate(order.received_time)
					business_info.courier_number = order.order_express_no
					let logistics_code = ""
					if (order.order_express === "顺丰速运") {
						logistics_code = "SF"
					}
					biz_content.logistics_info_list = {
						logistics_code: logistics_code,
						tracking_no: order.order_express_no
					}
					bsync = true
				}
			}
		}
		if (bsync) {
			orderDetailRes = await db.collection('wmzmall-order-detail').where({
				order_id: order.order_id
			}).get()
			orderDetailRes = orderDetailRes.data
			biz_content.item_order_list = await createIOL(orderDetailRes)
			ext_info = [{
				"ext_key": "merchant_order_status",
				"ext_value": merchant_order_status
			}, {
				"ext_key": "merchant_biz_type",
				"ext_value": merchant_biz_type
			}, {
				"ext_key": "merchant_order_link_page",
				"ext_value": "/sub-user/pages/order/order-detail?order_id="+order.order_id
			}, {
				"ext_key": "tiny_app_id",
				"ext_value": order.alipay_id
			}, {
				"ext_key": "business_info",
				"ext_value": JSON.stringify(business_info)
			}]
			biz_content.ext_info = ext_info
			if (order.discounts_price) {
				if (order.actually_shop_income < order.total_price) {
					biz_content.amount = order.actually_shop_income / 100 - order.discounts_price / 100
					biz_content.pay_amount = order.actually_shop_income / 100
					biz_content.discount_amount = order.discounts_price / 100
				} else {
					biz_content.amount = order.actually_shop_income / 100
					biz_content.pay_amount = order.actually_shop_income / 100
					biz_content.discount_amount = 0
				}
			} else {
				biz_content.amount = order.order_total_money / 100
				biz_content.pay_amount = order.order_total_money / 100
				biz_content.discount_amount = 0
			}
			syncData = {
				creator_id: order.create_uid,
				create_time: new Date().getTime(),
				app_id: order.app_id,
				shop_id: order.shop_id,
				alipay_id: order.alipay_id,
				order_id: order._id,
				buyer_id: order.order_member_openid,
				order_sync_data: biz_content,
				order_sync_status: 0,
				alipay_shop_id:order.alipay_shop_id
			}
			orderSyncRes = await db.collection('log-alipay-order-sync').add(syncData)
			let params = {
				app_id: order.app_id,
				url: 'alipay.merchant.order.sync',
				biz_content: biz_content
			}
			
			orderSync = await await wmzAlipaySdk.alipayRequestCommon(params)
			if (orderSync.data.code === "10000") {
				await db.collection('wmzmall-order')
					.doc(order._id)
					.update({
						order_sync: merchant_order_status
					});
				await db.collection('log-alipay-order-sync').doc(orderSyncRes.id).update({
					order_sync_status: 1,
					order_sync_reason: orderSync.data
				})
			} else {
				await db.collection('log-alipay-order-sync').doc(orderSyncRes.id).update({
					order_sync_status: 2,
					order_sync_reason: orderSync.data
				})
				await db.collection('wmzmall-order')
					.doc(order._id)
					.update({
						order_sync: order.order_sync + "_ERROR"
					});
			}
		}
	}
}

async function createIOL(order_content) {
	let goodDetails = []
	for (var i in order_content) {
		goodDetails.push({
			item_id: order_content[i].goods_id,
			item_name: order_content[i].goods_name,
			quantity: order_content[i].goods_num || 1,
			unit_price: order_content[i].goods_price / 100,
			ext_info: [{
				"ext_key": "image_material_id",
				"ext_value": "image_material_id"
			}]
		})
	}
	return goodDetails
}

async function formatdate(date, fmt) {
	if (typeof date === 'string') {
		date = date.replace(/\.|\-/g, '/');
	}
	if (typeof date !== 'object') {
		date = new Date(date);
		date.setHours(date.getHours() + 8);
	} 

	fmt = fmt || 'yyyy-MM-dd hh:mm:ss'
	let o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	};

	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (let k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[
				k]).length)));
	return fmt;
}
